package cn.qy.java.base.ch21;

import java.util.UUID;

/**
 * 同时开始的案例
 */
public class Ch21_07_SameStart {

	static class FireFlag {

		volatile boolean isStarted = false;

		public synchronized void ready() throws InterruptedException {
			// 使用 while，防止虚假唤醒
			while (!isStarted) {
				wait();
			}
		}

		public synchronized void fired() {
			isStarted = true;
			notifyAll();
		}

	}

	// 同时开始 1 结合 FireFlag 进行使用
	static class SameStartThread extends Thread {

		FireFlag fireFlag;

		public SameStartThread(FireFlag fireFlag) {
			this.fireFlag = fireFlag;
		}

		public void run() {
			try {
				this.fireFlag.ready();
				this.xxx();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		};

		// 同时开始
		private void xxx() {
			System.out.println("lalala" + UUID.randomUUID());
		}
	}
	
	// 同时开始 1 结合 MyLatch 进行使用
	static class SameStartThread2 extends Thread {

		Ch21_07_SameEnd.MyLatch latch;

		public SameStartThread2(Ch21_07_SameEnd.MyLatch latch) {
			this.latch = latch;
		}

		public void run() {
			try {
				this.latch.await();
				this.xxx();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		};

		// 同时开始
		private void xxx() {
			System.out.println("lalala" + UUID.randomUUID());
		}
	}

	public static void main(String[] args) throws InterruptedException {
	    System.out.println("---sameStart1---");
	    sameStart1();
	    
	    Thread.sleep(2000);
	    System.out.println("---sameStart2---");
	    
		sameStart2();
	}
	
	private static void sameStart1() throws InterruptedException {
		int size = 3;
		FireFlag flag = new FireFlag();
		for(int i = 0; i<size; i++) {
			new SameStartThread(flag).start();
		}
		Thread.sleep(1000);
		flag.fired();
	}
	
	private static void sameStart2() throws InterruptedException {
		int size = 5;
		Ch21_07_SameEnd.MyLatch latch = new Ch21_07_SameEnd.MyLatch(1);
		for(int i = 0; i<size; i++) {
			new SameStartThread2(latch).start();
		}
		Thread.sleep(1000);
		latch.countDown();
	}

}
